from engine.strategy import Strategy
from engine.datafeed import CSVDatafeed
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

instrument = '399905.SZ'
# 恒定市值维护
class FixMarketValueStrategy(Strategy):
    def __init__(self, feed):
        super(FixMarketValueStrategy, self).__init__(feed)
        self.fix_mv = 100000.0

    def onbar(self, index, date, df_bar):
        print(date)

        if index == 0:
            self.acc.order_buy_mv(instrument, 80000)

        # 取当前市值，若超过设定值，比如5万的10%，即55000，则卖掉5000，反之买入差额的部分
        # 取当前instrument的持仓市值，
        curr_mv = self.acc.get_instrument_mv(instrument)
        print(date, '当前持仓：{}'.format(round(curr_mv,2)), '现金：{}'.format(round(self.acc.curr_cash,2)))

        if curr_mv >= 1.1 * self.fix_mv:
            gap = curr_mv - self.fix_mv  # +5000
            self.acc.order_sell_mv(instrument, gap)
        elif curr_mv <= 0.9 * self.fix_mv:
            gap = self.fix_mv - curr_mv
            self.acc.order_buy_mv(instrument, gap)


feed = CSVDatafeed()
feed.add_data(instrument, '../datas/{}.csv'.format(instrument))

s = FixMarketValueStrategy(feed=feed)
s.run()
s.plot(benchmark=[instrument],filename='{}.html'.format(instrument))

